package com.cheetah.start.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Feel
 * @date 2021/12/8 20:21
 * @Description:
 */
@Slf4j
public class MyDingDingUtil {


    /**
     * 发送群消息
     *
     * @param e       e
     * @param request 请求
     */
    public static void send(Exception e, HttpServletRequest request) {
        String stackTrace = MyExceptionUtil.getStackTrackStr(e);
        String param = MyServletUtil.getParam(request);
        StringBuffer url = request.getRequestURL();
        contents(stackTrace, url + "\n参数:" + param);
    }


    /**
     * 内容必须包含 项目 两个字
     * https://oapi.dingtalk.com/robot/send?access_token=3300b1e577f4062e3d1d5b33457c2c6d2af6cc93939626ca4fbee1e323d0c6e3
     *
     * @param contents 内容
     */
    public static void notice(String contents, String url) {
        // 项目通知群钉钉机器人 webhook 消息内容必须包含 项目 关键字 post json 请求
        HashMap<String, Object> res = new HashMap<>();
        HashMap<String, Object> content = new HashMap<>();
        content.put("content", contents);
        res.put("msgtype", "text");
        res.put("text", content);
        String body = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .timeout(5000)
                .body(JSONObject.toJSONString(res)).execute().body();
        JSONObject result = JSONObject.parseObject(body);
        int errcode = result.getIntValue("errcode");
        if (errcode != 0) {
            log.warn("钉钉机器人通知失败:[{}]", body);
        }
    }


    /**
     * 内容
     * 发送内容规范
     *
     * @param val     异常信息
     * @param request 接口信息
     * @return {@link String}
     */
    public static String contents(String val, String request) {
        String timeFormat = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        String project = "项目:xxx系统\n";
        String time = "时间:" + timeFormat + "\n";
        return project + time + "异常信息:" + val + "\n" + "接口信息:" + request;
    }


}
